package com.example.demo.util.converters.impl;

import com.example.demo.util.converters.MyConverter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * @author 陈浩
 * @date 2021/1/9 15:59
 */

public class LocalDateConverter implements MyConverter<LocalDate> {
    @Override
    public LocalDate convertToJavaData(String value, Field declaredField) throws Exception {
        DateTimeFormat annotation = declaredField.getAnnotation(DateTimeFormat.class);
        String format = Optional.ofNullable(annotation).map(DateTimeFormat::pattern).orElse("");
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDate.parse(value, df);
    }

}
